package com.byd.dms.controller;

import com.alibaba.fastjson.JSONObject;
import com.byd.dms.entity.Dept;
import com.byd.dms.entity.Employee;
import com.byd.dms.entity.User;
import com.byd.dms.sf_json.entity.Emp2;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

@RestController
@RequestMapping("/http")
public class HttpController {
    
    @Autowired
    private HttpServletRequest request;
    
    @RequestMapping()
    public String index() {
        String data = request.getParameter("data");
        System.out.println("data = " + data);
        Enumeration<String> parameterNames = request.getParameterNames();
        List<String> list = Collections.list(parameterNames);
        System.out.println("list = " + Arrays.toString(list.toArray()));
        
        Emp2 emp2 = JSONObject.parseObject(data, Emp2.class);
        System.out.println("emp2 = " + emp2);
        
        Employee employee = JSONObject.parseObject(data, Employee.class);
        System.out.println("employee = " + employee);
        
        String userJson = request.getParameter("userJson");
        if (userJson != null) {
            User user = JSONObject.parseObject(userJson, User.class);
            System.out.println("user = " + user);
        }
        String deptJson = request.getParameter("deptJson");
        if (deptJson != null) {
            Dept dept = JSONObject.parseObject(deptJson, Dept.class);
            System.out.println("dept = " + dept);
        }
        return data;
    }
    
    @RequestMapping("/user")
    public User testUser() {
        
        // 接受解析参数
        
        return null;
    }
    
    
    @RequestMapping("/testRb")
    public Employee testRb(@RequestBody Employee employee) {
        // 接受解析参数
        return employee;
    }
    
    
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @RequestMapping("/testRb2")
    public Employee testRb2(HttpServletRequest request) throws IOException {
        
        System.out.println("Charset.defaultCharset() = " + Charset.defaultCharset());
        String json = StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset());
        System.out.println("json = " + json);
        Employee employee = objectMapper.readValue(json, Employee.class);
        
        
        return employee;
    }
}
